const productsNavSpan = document.getElementById("nav-span");
const productsTabsContainer = document.querySelector(".tab-item-box");
const productsTabItems = document.querySelectorAll(".tab-item");
const productsListViews = document.querySelectorAll(".products-list");
const productsContainer = document.querySelector(".products-container");

let urlParams = new URLSearchParams(window.location.search);
let position = urlParams.get("position");
if (position) {
  position = decodeURIComponent(position);
  position = position.replace(/"/g, "");
  console.log(position);

  // 初始化
  productsTabItems.forEach(function (tab, index) {
    if (index == position) {
      tab.classList.add("active");
      productsNavSpan.innerText = `> ${tab.innerText}`;
    } else {
      tab.classList.remove("active");
    }
  });

  productsListViews.forEach(function (list) {
    list.classList.remove("show");
  });
  const showListId = `products-list-${position}`;
  const showList = document.getElementById(showListId);
  showList.classList.add("show");
  
  productsContainer.scrollIntoView({
    behavior: "smooth",
    block: "start", // 元素在视窗中的位置：start/center/end
  });
}

productsTabItems.forEach(function (tabItem, index) {
  tabItem.addEventListener("click", function () {
    productsTabItems.forEach(function (tab) {
      tab.classList.remove("active");
    });
    productsListViews.forEach(function (list) {
      list.classList.remove("show");
    });
    const showListId = `products-list-${index}`;
    const showList = document.getElementById(showListId);
    showList.classList.add("show");
    this.classList.add("active");
    productsNavSpan.innerText = `> ${tabItem.innerText}`;

    scrollToCenter(tabItem);
  });

  function scrollToCenter(element) {
    // 小屏增加点击滚动到中间
    if (window.innerWidth <= 1200) {
      // 获取视窗宽度和元素位置信息
      const viewportWidth = window.innerWidth;
      const itemRect = element.getBoundingClientRect();
      // const containerRect = productsTabsContainer.getBoundingClientRect();

      // 计算需要滚动的距离
      const scrollLeft =
        productsTabsContainer.scrollLeft +
        itemRect.left -
        viewportWidth / 2 +
        itemRect.width / 2;

      // 滚动到计算出的位置
      productsTabsContainer.scrollTo({
        left: scrollLeft,
        behavior: "smooth",
      });
    }
  }
});
